# # -*- coding: utf-8 -*-
# import random
#
# import scrapy
# from scrapy import Request
# from scrapy.exceptions import IgnoreRequest
# from zc_core.dao.order_pool_dao import OrderPoolDao
# from zc_core.model.items import Order, Box, OrderStatus
# from zc_core.util.http_util import retry_request
# from esgcc.rules import *
# from esgcc.util.login import SeleniumLogin
# from zc_core.util.order_deadline_filter import OrderItemFilter
#
#
# class OrderItemSpider(BaseSpider):
#     name = 'order_item'
#     # 常用链接
#     order_list_url = 'http://b.esgcc.com.cn/showIndex/getLastestOrdersInner.htm?pgn={}'
#     order_detail_url = 'http://buser.esgcc.com.cn/order/detail?orderId={}'
#     allowed_domains = ['esgcc.com.cn']
#
#     def __init__(self, batchNo=None, *args, **kwargs):
#         super(OrderItemSpider, self).__init__(*args, **kwargs)
#         if not batchNo:
#             self.batch_no = time_to_batch_no(datetime.now())
#         else:
#             self.batch_no = int(batchNo)
#         self.order_filter = OrderItemFilter()
#
#     def start_requests(self):
#         cookies = SeleniumLogin().get_cookies()
#         # cookies = {'JSESSIONID': 'F456C70EA0DBB3849DEAA6434073E96C', '__d_s_': 'F456C70EA0DBB3849DEAA6434073E96C', '__s_f_c_s_': 'F456C70EA0DBB3849DEAA6434073E96C', '__t_c_k_': 'ace02bd7181e480395160deae448bee1'}
#         if not cookies:
#             self.logger.error('init cookie failed...')
#             return
#         self.logger.info('init cookie: %s', cookies)
#
#         # 处理订单列表
#         order_list = OrderPoolDao().get_todo_list(
#             batch_no=self.batch_no,
#             query={'workStatus': {'$ne': 1}, 'orderTime': {'$gt': self.order_filter.get_deadline()}},
#             fields={'_id': 1, 'orderTime': 1, 'orderDept': 1}
#         )
#         if order_list:
#             self.logger.info('目标：%s' % (len(order_list)))
#             random.shuffle(order_list)
#             for order in order_list:
#                 order_id = order.get('_id')
#                 order_time = order.get('orderTime')
#                 order_dept = order.get('orderDept')
#
#                 # 采集order明细页
#                 yield Request(
#                     url=self.order_detail_url.format(order_id),
#                     callback=self.parse_order_item,
#                     errback=self.error_back,
#                     cookies=cookies,
#                     headers={
#                         'Referer': 'http://buser.esgcc.com.cn/order/list'
#                     },
#                     meta={
#                         'reqType': 'order_item',
#                         'orderId': order_id,
#                         'orderDept': order_dept,
#                         'orderTime': order_time,
#                     },
#                     priority=200,
#                     dont_filter=True
#                 )
#
#     def parse_order_item(self, response):
#         meta = response.meta
#         order_id = meta.get('orderId')
#         order_time = meta.get('orderTime')
#
#         # 处理订单列表
#         orders = parse_order_item(response)
#         if orders:
#             yield Box('order_item', self.batch_no, orders)
#
#         # 标记订单已采
#         order_status = OrderStatus()
#         order_status['id'] = order_id
#         order_status['orderTime'] = order_time
#         order_status['batchNo'] = time_to_batch_no(order_time)
#         order_status['workStatus'] = 1
#         self.logger.info('完成: order=%s, item=%s' % (order_id, len(orders)))
#         yield order_status
#
#     # 错误处理
#     def error_back(self, e):
#         if e.type and e.type == IgnoreRequest:
#             self.logger.info(e.value)
#         else:
#             if e.request:
#                 self.logger.error('请求异常: [%s][%s] -> [%s]' % (str(type(e)), e.request.url, e.request.meta))
#                 yield retry_request(e.request)
#             else:
#                 self.logger.error('未知异常: %s' % e)
